package com.zhanglong.kotlinfish.Util.NetWork

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Handler

class ReachabilityUtil {

    interface ReachabilityCallBack {
        fun onLostNetWork()
    }
    private val context: Context
    private val handler = Handler()

    private var callBack: ReachabilityCallBack? = null

    constructor(context: Context) {
        this.context = context
    }

    private val RunnableOnLost = Runnable { callBack!!.onLostNetWork() }

    fun isReachable(context: Context?): Boolean {
        if (context != null) {
            val mConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = mConnectivityManager.activeNetworkInfo
            if (networkInfo != null) {
                return networkInfo.isAvailable
            }
        }
        return false
    }

    fun monitor(callBack: ReachabilityCallBack) {
        this.callBack = callBack
        val connectivityManager = this.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        connectivityManager?.requestNetwork(NetworkRequest.Builder().build(), object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                super.onAvailable(network)
            }

            override fun onLost(network: Network) {
                super.onLost(network)
                object : Thread() {
                    override fun run() {
                        handler.post(RunnableOnLost)
                    }
                }.start()
            }
        })
    }
}